package com.jzo2o.foundations.service.impl;/*
 * ClassName: ServeServiceImpl
 * Package: com.jzo2o.foundations.service.impl
 * Description:
 * @Author: LaiLai
 * @Create: 6/3/2024 - 下午4:43
 * @Version: V1.0
 */

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationIsHotEnum;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServeItemPageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeItemUpsertReqDTO;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import lombok.val;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Resource
    private ServeItemMapper serveItemMapper;

    @Resource
    private RegionMapper regionMapper;

    // @Resource
    // private IServeService service;


    /*
     * @ClassName IServeService
     * @Description: 分页查询服务列表
     * @params servePageQueryReqDTO 查询条件
     * @Return : 分页结果
       @Author : LaiLai
     * @Date : 6/3/2024 下午4:43
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        PageResult<ServeResDTO> serveResDTOPageResult = PageHelperUtils.selectPage(servePageQueryReqDTO, () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
        return serveResDTOPageResult;
    }

    /*
     * @ClassName ServeServiceImpl
     * @Description: 批量新增
     * @params List<ServeUpsertReqDTO> serveUpsertReqDTOList
     * @Return :
       @Author : LaiLai
     * @Date : 6/3/2024 下午11:55
     */
    @Override
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList) {
            //1.校验服务项是否为启用状态，不是启用状态不能新增
            ServeItem serveItem = serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
            //如果服务项信息不存在或未启用
            if(ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus()!= FoundationStatusEnum.ENABLE.getStatus()){
                throw new ForbiddenOperationException("该服务未启用无法添加到区域下使用");
            }

            //2.校验是否重复新增
            Integer count = lambdaQuery()
                    .eq(Serve::getRegionId, serveUpsertReqDTO.getRegionId())
                    .eq(Serve::getServeItemId, serveUpsertReqDTO.getServeItemId())
                    .count();
            if(count>0){
                throw new ForbiddenOperationException(serveItem.getName()+"服务已存在");
            }

            //3.新增服务
            Serve serve = BeanUtil.toBean(serveUpsertReqDTO, Serve.class);
            Region region = regionMapper.selectById(serveUpsertReqDTO.getRegionId());
            serve.setCityCode(region.getCityCode());
            baseMapper.insert(serve);
        }
    }

    /*
     * @ClassName ServeServiceImpl
     * @Description: 根据服务id删除服务
     * @params Long id
     * @Return :
       @Author : LaiLai
     * @Date : 6/3/2024 下午11:34
     */
    @Override
    public void deleteById(Long id) {
        //根据ID查询数据
        Serve serve = baseMapper.selectById(id);
        //判空
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("服务项不存在");
        }
        //删除
        baseMapper.deleteById(id);
    }

    /*
     * @ClassName ServeServiceImpl
     * @Description: 根据服务id，价格，对服务价格行修改
     * @params Long id, BigDecimal price
     * @Return :
       @Author : LaiLai
     * @Date : 6/3/2024 下午11:34
     */
    @Override
    public Serve update(Long id, BigDecimal price) {
        Serve serve = baseMapper.selectById(id);
        //判空
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("服务项不存在");
        }
        boolean updated = lambdaUpdate()
                .eq(Serve :: getId,id)
                .set(Serve :: getPrice,price)
                .update();
        if (ObjectUtil.isNull(updated)) {
            throw new ForbiddenOperationException("修改失败");
        }
        return baseMapper.selectById(id);



    }


    /*
     * @ClassName onSale
     * @Description: 根据服务id,对服务进行上架
     * @params Long id
     * @Return :
       @Author : LaiLai
     * @Date : 6/3/2024 下午11:57
     */
    @Override
    @Transactional
    public Serve onSale(Long id){
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //上架状态
        Integer saleStatus = serve.getSaleStatus();
        //草稿或下架状态方可上架
        if (!(saleStatus==FoundationStatusEnum.INIT.getStatus() || saleStatus==FoundationStatusEnum.DISABLE.getStatus())) {
            throw new ForbiddenOperationException("草稿或下架状态方可上架");
        }
        //服务项id
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        //服务项的启用状态
        Integer activeStatus = serveItem.getActiveStatus();
        //服务项为启用状态方可上架
        if (!(FoundationStatusEnum.ENABLE.getStatus()==activeStatus)) {
            throw new ForbiddenOperationException("服务项为启用状态方可上架");
        }

        //更新上架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("启动服务失败");
        }
        return baseMapper.selectById(id);
    }

    /*
     * @ClassName ServeServiceImpl
     * @Description: 对服务进行下架
     * @params Long id
     * @Return : Serve
       @Author : LaiLai
     * @Date : 12/3/2024 下午3:01
     */
    @Override
    public Serve offSale(Long id) {
        Serve serve = baseMapper.selectById(id);
        //判断是否为空
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //判断服务状态
        Integer saleStatus = serve.getSaleStatus();
        //草稿或下架状态方可上架
        if ((saleStatus!=FoundationStatusEnum.ENABLE.getStatus())) {
            throw new ForbiddenOperationException("启用状态方可下架");
        }
        //服务项id
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        //更新上架状态
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if(!update){
            throw new CommonException("下架服务失败");
        }
        return baseMapper.selectById(id);
    }

    /*
     * @ClassName ServeServiceImpl
     * @Description: 设置服务热门
     * @params Long id
     * @Return : Serve
       @Author : LaiLai
     * @Date : 12/3/2024 下午3:00
     */
    @Override
    public Serve onHot(Long id) {
        Serve serve = baseMapper.selectById(id);
        //判断是否为空
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //服务项id
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        //服务项的启用状态
        Integer activeStatus = serveItem.getActiveStatus();
        //服务项为启用状态方可设置热门
        if (!(FoundationStatusEnum.ENABLE.getStatus()==activeStatus)) {
            throw new ForbiddenOperationException("服务项为启用状态方可设置热门");
        }
        //对热门进行判断，如果服务已经是热门，则不允许进行设置热门
        //获取当前的热门的状态
        Integer isHotStatus = serve.getIsHot();
        if (isHotStatus == FoundationIsHotEnum.HOT.getStatus() || isHotStatus == null){
            throw new ForbiddenOperationException("服务不可设置热门");
        }
        //进行设置热门
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, FoundationIsHotEnum.HOT.getStatus())
                .update();
        if (!update){
            throw new  CommonException("设置服务热门失败");
        }
        return baseMapper.selectById(id);
    }

    /*
     * @ClassName ServeServiceImpl
     * @Description: 设置服务的取消热门
     * @params Long id
     * @Return : Serve
       @Author : LaiLai
     * @Date : 12/3/2024 下午3:01
     */
    @Override
    public Serve offHot(Long id) {
        Serve serve = baseMapper.selectById(id);
        //判断是否为空
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //服务项id
        Long serveItemId = serve.getServeItemId();
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);
        if(ObjectUtil.isNull(serveItem)){
            throw new ForbiddenOperationException("所属服务项不存在");
        }
        //服务项的启用状态
        Integer activeStatus = serveItem.getActiveStatus();
        if ((activeStatus!= FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("状态为启用才可以进行取消热门设置");
        }
        //获取当前的热门的状态
        Integer isHotStatus = serve.getIsHot();

        //状态不为热门，则不可以进行取消热门
        if (isHotStatus==FoundationIsHotEnum.NoHot.getStatus() || isHotStatus == null){
            throw new ForbiddenOperationException("设置服务取消热门失败");
        }
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, FoundationIsHotEnum.NoHot.getStatus())
                .update();
        if (!update){
            throw new  CommonException("设置服务取消热门失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 根据区域id和售卖状态查询关联服务数量
     *
     * @param regionId   区域id
     * @param saleStatus 售卖状态，0：草稿，1下架，2上架。可传null，即查询所有状态
     * @return 服务数量
     */
    @Override
    public int queryServeCountByRegionIdAndSaleStatus(Long regionId, Integer saleStatus) {
        LambdaQueryWrapper<Serve> queryWrapper = Wrappers.<Serve>lambdaQuery()
                .eq(Serve::getRegionId, regionId)
                .eq(ObjectUtil.isNotEmpty(saleStatus), Serve::getSaleStatus, saleStatus);
        return baseMapper.selectCount(queryWrapper);
    }

    /**
     * 根据服务项id和售卖状态查询关联服务数量
     *
     * @param  serveItemId  服务项id
     * @param saleStatus 售卖状态，0：草稿，1下架，2上架。可传null，即查询所有状态
     * @return 服务数量
     */
    @Override
    public int queryServeCountByServeItemIdAndSaleStatus(Long serveItemId, Integer saleStatus) {
        LambdaQueryWrapper<Serve> queryWrapper = Wrappers.<Serve>lambdaQuery()
                .eq(Serve::getServeItemId, serveItemId)
                .eq(ObjectUtil.isNotEmpty(saleStatus), Serve::getSaleStatus, saleStatus);
        return baseMapper.selectCount(queryWrapper);
    }
}
